package com.imooc.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * AOP处理;
 * 1.添加依赖
 * 2.建立类，添加@Aspect注解，并将其加入容器@Component
 */
@Aspect
@Component
public class HttpAspect {
//    //@Before("execution(public * com.imooc.controller.GirlController.girlList(..))")//拦截girlList方法
//    @Before("execution(public * com.imooc.controller.GirlController.*(..))")//拦截方法， ..代表任意参数
//    public void log() {
//        System.out.println("1111");
//    }
//
//    @After("execution(public * com.imooc.controller.GirlController.*(..))")
//    public void doAfter() {
//        System.out.println("2222");
//    }

    /**
     * 上面代码每次都要写execution(public * com.imooc.controller.GirlController.*(..))
     * 下面优化一下
     * 并且，不再使用println输出，而是使用日志
     */
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
    @Pointcut("execution(public * com.imooc.controller.GirlController.*(..))")//拦截方法
    public void log() {
    }
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        logger.info("before");
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        logger.info("url={}",request.getRequestURL());
        //method
        logger.info("method={}",request.getMethod());
        //ip
        logger.info("ip={}",request.getRemoteAddr());
        //类方法
//        JoinPoint joinPoint = null;
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName() + "." +
                joinPoint.getSignature().getName());
        //参数
        logger.info("arg={}", joinPoint.getArgs());
    }

    @After("log()")
    public void doAfter() {
        logger.info("after");
    }
    //获取返回的信息
    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        logger.info("response={}",object.toString());
    }
}
